from im import *
from collections import defaultdict
from numpy import *

T = []
labels = "0123456789abcdefghijklmnopqrstuvwxyz"
for r in range(36):
  for c in range(20):
    image = crop(r, c)
    T.append((image, labels[r]))

def vec(x):
  return x.reshape(x.shape[0]*x.shape[1])
def sim(x, u):
  xvec = vec(x)
  uvec = vec(u)
  if dot(xvec, xvec) == 0:
    return 0
  return float(dot(xvec, uvec))/sqrt(dot(xvec, xvec)*dot(uvec, uvec))
  
def classify(u, k=30):
  S = []
  for (x, label) in T:
    S.append((sim(x, u), label))
  labels = [y[1] for y in sorted(S, reverse=1)[:k]]
  
  count = defaultdict(int)
  for label in labels:
    count[label] += 1
  return [[_[1], _[0]] for _ in sorted([(v, k) for (k,v) in count.items()], reverse=1)[:3]]

if __name__ == '__main__':
  import sys
  from pylab import *
  r = labels.index(sys.argv[1][0])
  c = int(sys.argv[2])
  u = crop(r, c)
  imshow(u)
  print classify(u)
  show()